package com.cuiweiyou.arduinogirl.bluetooth;

import android.bluetooth.le.ScanResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

public class BluetoothRssiSortor {

    /**
     * 根据信号强度排序
     */
    public static List<ScanResult> sortDevicesByRssi(Map<String, ScanResult> bluetoothDeviceMap) {
        List<Map.Entry<String, ScanResult>> list = new ArrayList<>(bluetoothDeviceMap.entrySet());
        Collections.sort(list, rssiComparator);

        List<ScanResult> bluetoothDeviceList = new ArrayList<>();
        for (Map.Entry<String, ScanResult> mapping : list) {
            ScanResult device = mapping.getValue();
            bluetoothDeviceList.add(device);
        }

        return bluetoothDeviceList;
    }

    private static Comparator rssiComparator = new Comparator<Map.Entry<String, ScanResult>>() {

        @Override
        public int compare(Map.Entry<String, ScanResult> sr1, Map.Entry<String, ScanResult> sr2) {
            ScanResult v1 = sr1.getValue();
            ScanResult v2 = sr2.getValue();
            int rssi1 = v1.getRssi();
            int rssi2 = v2.getRssi();
            return Integer.compare(rssi2, rssi1);
        }
    };
}
